<template>
    <a-modal :keyboard="false" :maskClosable="false" title="项目关联" :open="visible" :width="550" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="项目名称">
                        <a-input v-model:value="modelRef.projectName" disabled style="width: 100%" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item label="关联项目" v-bind="validateInfos.relationProjectCodes">
                        <a-tree-select
                            v-model:value="modelRef.relationProjectCodes"
                            style="width: 100%"
                            tree-checkable
                            :height="233"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'code',
                            }"
                            :tree-data="buildData"
                            :max-tag-count="10"
                        ></a-tree-select>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, nextTick } from 'vue';
    import { Form, message, Cascader } from 'ant-design-vue';
    import { updateProjectRelation, createProjectRelation, getProjectRelation } from '@/api/user/project-relation';
    import { cloneDeep, isUndefined, isEmpty } from 'lodash-es';
    import { queryWbTree } from '@/api/common/mdm';
    import { mapTree, flatten, toTreeArray } from 'xe-utils';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<CreateMenuParams | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const buildData = ref<any[]>([]);

            const defaultForm = {
                relationProjectCodes: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                relationProjectCodes: [{ required: true, message: '请选择' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    queryWbTree().then(res => {
                        if (res.data.code) {
                            nextTick(() => {
                                buildData.value = mapTree([res.data], item => ({
                                    ...item,
                                    label: item.name,
                                    value: item.code,
                                }));
                            });
                        }
                    });
                    if (props.model) {
                        if (props.model.projectCode) {
                            getProjectRelation(props.model.projectCode).then(res => {
                                Object.assign(modelRef, res.data);
                            });
                        }
                    }
                }
            });
            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, { ...cloneDeep(defaultForm) });
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;
                    const { projectCode, relationProjectCodes } = modelRef;
                    const params: any = {
                        projectCode,
                        relationProjectCodes,
                    };
                    // const flattenCodes = flatten(modelRef.relationProjectCodes);
                    // if (flattenCodes.length === 1) {
                    //     if (flattenCodes[0] === buildData.value[0].code) {
                    //         params.relationProjectCodes = flatten(toTreeArray(buildData.value).map(item => item.code));
                    //     }
                    // } else {
                    //     params.relationProjectCodes = flattenCodes;
                    // }
                    updateProjectRelation(params)
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,

                buildData,
            };
        },
    });
</script>
